<!--支付单列表详情、付款页-->
<template>
  <div class="invoice-list-box">
    <el-container class="partDetails is-vertical">
      <el-header
        class="common-ui"
        height="auto">
        <record-info
          :record-form="nissinReadColunmns"
          :record-data="headerInfo" />
      </el-header>
      <div class="common-ui">
        <h3 style="padding: 8px;">付款记录</h3>
        <el-editable
          class="distributor-edit-box"
          :data="paymentrecordList"
          height="300"
          v-loading="tableLoading"
          :columns="collectionColumns"
        />
      </div>
      <div class="common-ui">
        <h3 style="padding: 8px;">关联发票</h3>
        <el-editable
          ref="table"
          class="distributor-edit-box"
          :data="invoiceList"
          height="300"
          v-loading="tableLoading"
          :columns="invoiceColumns"
        >
          <!-- 发票详情 -->
          <template
            slot="default-invoiceList"
            slot-scope="scope">
            <el-button
              @click="toLookDetailsList(scope.row)"
              type="text">查看</el-button>
          </template>
          <!-- 发票影像 -->
          <template
            slot="default-invoicePng"
            slot-scope="scope">
            <div style="display:flex; justify-content: center;">
              <el-image
                v-if="scope.row.invoiceUrl"
                @click="toLookDetails(scope.row)"
                style="width: 23px; height: 16.6px;"
                :src="imageicon"/>
            </div>
          </template>
        </el-editable>
      </div>
    </el-container>
    <!--付款弹窗-->
    <el-dialog
      title="财务付款"
      :visible.sync="showPayment"
      width="550px"
      :before-close="cancel">
      <el-form
        :model="receiptForm"
        label-width="120px">
        <el-form-item label="供应商名称：">
          <span>{{ headerInfo.distributorName }}</span>
        </el-form-item>
        <div style="display:flex;">
          <el-form-item label="应付总金额：">
            <span style="margin-right:100px;">{{ headerInfo.invoiceAmount }}</span>
          </el-form-item>
          <el-form-item label="剩余付款金额：">
            <!-- <span>{{ remainMoney }}</span> -->
            <!-- <p>{{ surplusMoney ? surplusMoney.toFixed(3) : 0 }}</p> -->
            <span>{{ surplusMoney }}</span>
          </el-form-item>
        </div>
        <div style="width:400px;">
          <el-form-item label="本次付款：">
            <el-input-number
              :controls="false"
              :precision="3"
              v-model="receiptForm.paymentMoney"
              placeholder="请输入内容："
            />
          </el-form-item>
          <el-form-item label="备注：">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入"
              v-model="receiptForm.paymentRemarks"
            />
          </el-form-item>
        </div>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button
          type="primary"
          @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>
    <invoice-details
      :display-or-not="displayOrNotDetails"
      :invoice-url="activeInvoiceUrl"
      :busness-type="1"
      :invoice-no="activeInvoiceNo"
      @cancelDialog="cancelDialog" />
  </div>
</template>

<script>
import {
  hospitalSettleQuaryTradePayDetail,
  hospitalSettleInsertTradePayHistory // 医院-后结算-保存支付订单支付记录（付款）
} from '@const/beforeSettleApi'
import { paymentbaseList, paymentrecordColums, nissinReadColunmns, collectionColumns, invoiceColumns } from './const'
import { getFormatterPrice } from '@const/filter'
import ElEditable from '@components/el-editable'
import RecordInfo from '@/moduleComponents/beforeSettle/distributorSide/purchasingManagement/record'
import InvoiceDetails from '@/moduleComponents/beforeSettle/invoiceDetails'
export default {
  components: { ElEditable, InvoiceDetails, RecordInfo },
  data () {
    return {
      // 影像弹窗
      imageicon: require('@assets/icon/beforeSettle/imageicon.png'),
      readPath: '/hospitalSide/purchaseManagement/orderpayableList/read',
      // 查看发票详情
      displayOrNotDetails: false,
      activeInvoiceUrl: '',
      activeInvoiceNo: '',
      // 基本信息
      nissinReadColunmns,
      headerInfo: {},
      // 付款记录
      paymentrecordList: [],
      collectionColumns,
      // 发票
      invoiceList: [],
      invoiceColumns,
      // 付款信息
      receiptForm: {
        paymentMoney: '', // 本次付款金额
        paymentRemarks: '' // 付款备注
      },
      tableLoading: false,
      showPayment: false, // 是否显示弹窗
      payAllMoney: 0, // 应付总金额
      remainMoney: 0, // 剩余付款金额
      judgeMoney: 0
    }
  },
  computed: {
    surplusMoney () {
      let num = null
      if (this.paymentrecordList.length !== 0) {
        num = this.paymentrecordList[0].surplusAmount
        if (num > 0) {
          num = num.toFixed(3)
        }
      } else {
        num = this.headerInfo.invoiceAmount || null
      }
      return num
    }
  },
  mounted () {
    this.setBtn()
    this.getDeatil()
  },
  filters: {
    getFormatterPrice
  },

  methods: {
    setBtn () {
      // let arr = [{ type: '', val: '返回', handle: () => this.$router.go(-1) }]
      let arr = []
      // 判断是否是付款
      if (this.$route.query.type === 'pay') {
        arr = [
          { type: '', val: '返回', handle: () => this.$router.go(-1) },
          { type: 'primary', val: '付款', handle: this.payment }
        ]
      } else {
        arr = [{ type: '', val: '返回', handle: () => this.$router.go(-1) }]
      }

      this.$store.commit('changeLayoutHandle', {
        type: 'btn',
        arr: arr
      })
    },
    // 查看发票详情
    toLookDetailsList (data) {
      // 跳转地址-应收单详情
      this.$router.push({
        path: '/hospitalSide/purchaseManagement/common/invoiceDetails',
        query: {
          id: data.receiptPayId,
          invoiceNo: data.invoiceNo
        }
      })
    },
    // 获取详情
    getDeatil () {
      this.$axios.$post(hospitalSettleQuaryTradePayDetail, {
        tradeId: this.$route.query.id,
        receiptPayId: this.readPath
        // payIdList: [],
        // page: 1,
        // pageSize: 1
      })
        .then(res => {
          // 付款记录
          this.paymentrecordList = res.payload.tradeHistory || []
          this.invoiceList = res.payload.invoiceList || []
          // 支付单数据
          this.headerInfo = res.payload
          // 用来判断是否超出剩余金额的标准
          this.judgeMoney =
            this.paymentrecordList === null ||
            this.paymentrecordList.length === 0
              ? this.headerInfo.invoiceAmount
              : this.paymentrecordList[0].surplusAmount === null ||
                this.paymentrecordList[0].surplusAmount === 0
                ? 0
                : this.paymentrecordList[0].surplusAmount

          this.paymentListDeal()

          // 付款明细
          this.paymentrecordDetail = res.payload.tradeHistory || []
          this.paymentrecordDetail.forEach(item => {
            item.invoiceAmountTax =
              item.invoiceAmountTax === null
                ? '--'
                : '￥' + getFormatterPrice(item.invoiceAmountTax)
          })
        })
        .catch(err => {
          console.log(err)
        })
    },
    cancel () {
      this.showPayment = false
      this.receiptForm = {
        paymentMoney: '',
        paymentRemarks: ''
      }
    },
    // 弹窗确定
    confirm () {
      if (this.receiptForm.paymentMoney === '') {
        this.$message({
          type: 'warning',
          message: '请输入本次付款金额'
        })
      } else if (this.receiptForm.paymentMoney > 0) {
        if (this.receiptForm.paymentMoney > this.judgeMoney) {
          this.$message({
            type: 'warning',
            message: '本次付款金额不得高于剩余金额'
          })
        } else {
          this.$axios
            .$post(hospitalSettleInsertTradePayHistory, {
              tradeId: this.$route.query.id,
              tradeAmount: this.receiptForm.paymentMoney,
              remarks: this.receiptForm.paymentRemarks
            })
            .then(res => {
              if (res.msg === 'ok') {
                this.$message({
                  type: 'success',
                  message: '付款成功'
                })
                this.cancel()
                this.getDeatil()
              }
            })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '本次付款金额必须大于0'
        })
      }
    },
    // 查看发票详情
    toLookDetails (val) {
      this.activeInvoiceUrl = val.invoiceUrl
      this.activeInvoiceNo = val.invoiceNo
      this.displayOrNotDetails = true
    },
    cancelDialog () {
      this.activeInvoiceUrl = ''
      this.activeInvoiceNo = ''
      this.displayOrNotDetails = false
      this.getDeatil()
    },
    // 支付单产品金额和发票金额处理
    paymentListDeal () {
      // 支付单数据中发票金额
      this.headerInfo.invoiceAmount =
        this.headerInfo.invoiceAmount === null
          ? '--'
          : (this.headerInfo.invoiceAmount).toFixed(3)
      // 支付单数据中产品金额
      // this.headerInfo.prodTotalAmount =
      //   this.headerInfo.prodTotalAmount === null
      //     ? '--'
      //     : '￥' + getFormatterPrice(this.headerInfo.prodTotalAmount)
    },
    // 付款
    payment () {
      if (
        this.paymentrecordList === null ||
        !this.paymentrecordList[0] ||
        Number(this.paymentrecordList[0].surplusAmount) > 0
      ) {
        this.showPayment = true
      } else if (this.paymentrecordList[0].surplusAmount === 0) {
        this.$message.warning('付款已完成不可重复操作！')
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import '../m-front-common/pc/assets/var.less';
.invoice-list-box {
  background: @bgColor;
  height: 100%;
  position: absolute;
  overflow: auto;
  /deep/.el-dialog {
    .el-dialog__body {
      padding: 0 8px;
      // justify-content: space-between;
      p {
        margin: 8px 0;
      }
    }
  }
  .common-ui {
    background: #fff;
    margin-bottom: 8px;
  }
}
</style>
